package shared.implicits

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import ujson.{Null, Num, Str}

import upickle.default._

import scala.collection.immutable.SeqMap

/**
 * Created by Administrator on 2019/11/11
 */

trait MyUJsonTool {

  implicit def dateTimeReadWrite: ReadWriter[DateTime] = {
    val pattern = "yyyy-MM-dd HH:mm:ss"
    readwriter[ujson.Str].bimap[DateTime](x => {
      ujson.Str(x.toString(pattern))
    }, y => {
      val formatter = DateTimeFormat.forPattern(pattern)
      formatter.parseDateTime(y.str)
    })
  }

  implicit class MyObj(obj: ujson.Obj) {

    def ++(otherObj: ujson.Obj) = {
      ujson.Obj(obj.value ++ otherObj.value)
    }

  }

  implicit class MyValue(v: ujson.Value) {

    def toArr = {
      v.transform(reader[ujson.Arr])
    }

    def toObj = {
      v.transform(reader[ujson.Obj])
    }

    def myStr = {
      v match {
        case Str(value) => value
        case Null => "-"
        case ujson.Obj(x) => x.toString()
        case ujson.Num(x) => x.toString()
      }
    }

    def numStr = v.num.toString

  }


}
